package com.tiance.web.controller.back;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.ActivityDO;
import com.tiance.dal.dataobject.TaskDO;
import com.tiance.dal.dataobject.UserDO;
import com.tiance.domainservice.checker.ActivityChecker;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.checker.TaskChecker;
import com.tiance.domainservice.domain.ActivityDomain;
import com.tiance.domainservice.domain.TaskDomain;
import com.tiance.domainservice.service.ActivityService;
import com.tiance.domainservice.service.TaskService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.Validator;
import com.tiance.vo.ActivityVO;
import com.tiance.vo.TaskVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.BackController;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：任务管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/back/task")
public class BackTaskController extends BackController {

    private static String LOG_PREFIX ="BackTaskController| 任务控制器===>";

    @Autowired
    private TaskService taskService;


    @RequestMapping(value = "/toApplyTaskList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:task")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到任务申请列表页面")
    public String toApplyTaskList() {
        return "/back/content/task/taskApplyList";
    }


    @RequestMapping(value = "/toTaskList.action",method = RequestMethod.GET)
    @RequiresPermissions("menu:content:task")
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="跳转到已发布任务列表页面")
    public String toTaskList() {
        return "/back/content/task/taskList";
    }


    @RequestMapping(value = "/addTask.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询任务")
    public BaseResponse addTask(HttpServletRequest request, TaskVO taskVO){
        logger.info("开始新建任务列表，请求参数:{}", JSON.toJSONString(taskVO));

        BaseResponse<TaskDO> backResponse=new BaseResponse<>();
        try {
            Session session = SecurityUtils.getSubject().getSession();
            UserDO userDO=(UserDO)session.getAttribute(CommonConstants.USER);
            taskVO.setApplicantId(userDO.getId());
            taskVO.setApplicantType(ApplicantTypeEnum.SYSTEM.getCode());
            TaskChecker.checkAddTask(taskVO);
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
           taskService.addTask(taskDomain);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"新建任务失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"新建任务失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("新建任务失败");
        }
        logger.info("结束新建任务，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }



    @RequestMapping(value = "/queryTaskApplyList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询任务申请列表")
    public BaseResponse queryTaskApplyList(TaskVO taskVO, QueryPage queryPage){
        logger.info("开始查询任务申请列表，请求参数:{}", JSON.toJSONString(taskVO));

        BaseResponse<TaskDO> backResponse=new BaseResponse<>();
        try {
            MemberParamsChecker.checkPageQuery(queryPage);
            taskVO.setQueryPage(queryPage);

            List<String> status = Arrays.asList(TaskStatusEnum.UN_AUDIT.getCode());
            taskVO.setStatusScope(status);
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            List<TaskDO> taskDOList= taskService.queryTaskList(taskDomain);
            backResponse.setResultList(taskDOList);
            backResponse.setQueryPage(taskDomain.getQueryPage());
            backResponse.setTotalRecord(taskDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询任务申请列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询任务申请列表列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询任务申请列表失败");
        }
        logger.info("结束查询任务申请列表列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/queryTaskList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询任务")
    public BaseResponse queryTaskList(TaskVO taskVO, QueryPage queryPage){
        logger.info("开始查询任务列表，请求参数:{}", JSON.toJSONString(taskVO));

        BaseResponse<TaskDO> backResponse=new BaseResponse<>();
        try {
            MemberParamsChecker.checkPageQuery(queryPage);
            taskVO.setQueryPage(queryPage);

            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            List<TaskDO> taskDOList= taskService.queryTaskList(taskDomain);
            backResponse.setResultList(taskDOList);
            backResponse.setQueryPage(taskDomain.getQueryPage());
            backResponse.setTotalRecord(taskDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询任务列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询任务列表列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询任务列表失败");
        }
        logger.info("结束查询任务列表列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/cancelTask.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消任务")
    public BaseResponse cancelTask( TaskVO taskVO){
        logger.info("开始取消任务，请求参数:{}", JSON.toJSONString(taskVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(taskVO.getId(),"任务ID不能为空!");
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            if(MapCacheUtil.lock(taskVO.getId() + EntityTypeEnum.TASK.getCode())) {
                taskService.cancel(taskDomain);
            }else {
                throw new BusinessException("该任务正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消任务失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"取消任务失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("取消任务失败");
        }finally {
            MapCacheUtil.unlock(taskVO.getId()+EntityTypeEnum.TASK.getCode());
        }
        logger.info("结束取消任务，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/finishTask.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="结束任务")
    public BaseResponse finishTask( TaskVO taskVO){
        logger.info("开始结束任务，请求参数:{}", JSON.toJSONString(taskVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(taskVO.getId(),"任务ID不能为空!");
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            if(MapCacheUtil.lock(taskVO.getId() + EntityTypeEnum.TASK.getCode())) {
                taskService.finish(taskDomain);
            }else {
                throw new BusinessException("该任务正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"结束任务失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"结束任务失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("结束任务失败");
        }finally {
            MapCacheUtil.unlock(taskVO.getId()+EntityTypeEnum.TASK.getCode());
        }
        logger.info("结束结束任务，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }

}